﻿using System;
using System.Web.Mvc;

namespace OperationPlugins.Mvc.Filters
{
    /// <summary>
    /// Used to specify the <see cref="BranchId"/> for the current action method.
    /// 
    /// To use this, apply this attribute to an action method or to a controller class.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class CurrentBranchAttribute : FilterAttribute, IAuthorizationFilter
    {
        private readonly string _value;
        private BranchId _branch;

        /// <summary>
        /// Initializes a new instance of the CurrentBranchAttribute class.
        /// </summary>
        /// <param name="branchId">BranchId</param>
        public CurrentBranchAttribute(string branchId)
        {
            if (branchId == null)
            {
                throw new ArgumentNullException("branchId");
            }

            _value = branchId;
        }

        /// <summary>
        /// Gets the BranchId.
        /// </summary>
        public virtual string Value
        {
            get { return _value; }
        }

        /// <summary>
        /// Gets the BranchId.
        /// </summary>
        protected virtual BranchId Branch
        {
            get { return _branch ?? (_branch = new BranchId(Value)); }
        }

        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
        {
            OperationPluginsContext.Current.CurrentActionBranch = Branch;
        }

    }
}
